<?php
// session_start();
header('Content-type: application/json');
require_once("../lib/standard.php");
require_once("../fantasmatakia/pektis.php");
require_once("../lib/partida.php");
require_once("../lib/theatis.php");
require_once("../lib/sizitisi.php");

define('DEDOMENA_APO_FILE', 0);
define('DEDOMENA_APO_DB', 1);

define('DATA_PARTIDA', '@PARTIDA@');
define('DATA_THEATIS', '@THEATIS@');
define('DATA_SIZITISI', '@SIZITISI@');
define('DATA_END', '@@');

define('POLLING_TIC', 200);
define('POLLING_MAX_TIME', 40);

$globals->pektis = new Pektis();
$globals->pektis->login = Globals::parametros("login");
$globals->pektis->set_poll();
$freska = Globals::perastike("freska", FALSE); 

$fdata = $freska ? NULL : new Dedomena(DEDOMENA_APO_FILE);
$begin_ts = time();
while (TRUE) {
	$dbdata = new Dedomena(DEDOMENA_APO_DB);
	if (isset($fdata)) { $fdata->trepart = $dbdata->trepart; }
	if ($dbdata != $fdata) {
		break;
	}

	if ((time() - $begin_ts) > POLLING_MAX_TIME) {
		arxi_apostolis();
		print(",same:true");
		telos_apostolis();
	}

	usleep(POLLING_TIC);
}

$dbdata->enimerosi_arxiou();
arxi_apostolis();
stile_data($dbdata, $fdata);
telos_apostolis();

function arxi_apostolis() {
	print "dummy:0";
}

function telos_apostolis() {
	die("@OK");
}

function stile_data($dbdata, $fdata) {
	print ",tp:" . $dbdata->trepart;
	if (isset($fdata)) {
		stile_data_partida($dbdata->partida, $fdata->partida);
		stile_data_theatis($dbdata->theatis, $fdata->theatis);
		stile_data_sizitisi($dbdata->trepart, $dbdata->sizitisi, $fdata->sizitisi);
	}
	else {
		stile_data_partida($dbdata->partida);
		stile_data_theatis($dbdata->theatis);
		stile_data_sizitisi($dbdata->trepart, $dbdata->sizitisi);
	}
}

function stile_data_partida($db, $f = array()) {
	if ($db == $f) {
		return;
	}

	$db_assoc = array();
	$f_assoc = array();

	$add = array();
	$mod = array();

	$n = count($db);
	for($i = 0; $i < $n ; $i++) {
		$db_assoc[$db[$i]->id] = $i;
	}

	$n = count($f);
	for($i = 0; $i < $n ; $i++) {
		$f_assoc[$f[$i]->id] = $i;
	}

	foreach ($db_assoc as $id => $i) {
		if (!array_key_exists($id, $f_assoc)) {
			$add[$id] = $i;
			continue;
		}

		if ($db[$db_assoc[$id]] != $f[$f_assoc[$id]]) {
			$mod[$id] = $i;
		}

		unset($f_assoc[$id]);
	}

	if (count($add) + count($mod) + count($f_assoc) >= count($db)) {
		print ",partida:[";
		$koma = "";
		for ($i = count($db) - 1; $i >= 0; $i--) {
			print $koma;
			$db[$i]->json();
			$koma = ",";
		}
		print "]";
		return;
	}

	if (count($add) > 0) {
		$koma = ",partidaAdd:[";
		foreach ($add as $i) {
			print $koma;
			$db[$i]->json();
			$koma = ",";
		}
		print "]";
	}

	if (count($mod) > 0) {
		$koma = ",partidaMod:[";
		foreach ($mod as $i) {
			print $koma;
			$db[$i]->json();
			$koma = ",";
		}
		print "]";
	}

	if (count($f_assoc) > 0) {
		$koma = ",partidaDel:[";
		foreach ($f_assoc as $id => $i) {
			print $koma;
			print $id;
			$koma = ",";
		}
		print "]";
	}
}

function stile_data_theatis($db, $f = array()) {
}

function stile_data_sizitisi($tp, $db, $f = -1) {
	global $globals;
	$koma = ",s:[";
	$telos = "";
	$query = "SELECT `pektis`, `kimeno` FROM `sizitisi` WHERE `partida` = " .
		$tp . " AND `id` > " . $f . " AND `id` <= " . $db .
		" ORDER BY `id` ASC";
	$result = $globals->query($query);
	while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
		print $koma . "{p:'" . Globals::json_safe($row["pektis"]) .
			"',k:'" . Globals::json_safe($row["kimeno"]) . "'}";
		$koma = ",";
		$telos = "]";
	}
	print $telos;
}

class Dedomena {
	public $partida;
	public $theatis;
	public $sizitisi;
	public $trepart;
	public $thesi;

	public function __construct($source) {
		$this->partida = array();
		$this->theatis = array();
		$this->sizitisi = -1;
		$this->trepart = NULL;
		$this->thesi = NULL;

		switch ($source) {
		case DEDOMENA_APO_FILE:
			$this->diavase_arxio();
			break;
		case DEDOMENA_APO_DB:
			$this->diavase_db();
			break;
		default :
			die("Dedomena: construct: invalid mode");
			break;
		}
	}

	private function diavase_arxio() {
		global $globals;

		$fp = self::anixe_arxio("r");
		if (!$fp) { return; }

		while ($buf = Globals::get_line($fp)) {
			switch ($buf) {
			case DATA_PARTIDA:
				$this->partida = self::diavase_arxio_partides($fp);
				break;
			case DATA_THEATIS:
				$this->theatis = self::diavase_arxio_theates($fp);
				break;
			case DATA_SIZITISI:
				$this->sizitisi = self::diavase_arxio_sizitisi($fp);
				break;
			default:
				die("BAD HEADER (" . $buf . ")");
			}
		}

		fclose($fp);
	}

	private static function anixe_arxio($mode) {
		global $globals;

		$fname = "../dedomena/" . $globals->pektis->login;
		return fopen($fname, $mode);
	}

	private static function diavase_arxio_partides($fp) {
		$partida = array();
		while ($buf = self::get_line($fp)) { 
			$p = new Partida($buf);
			if (!isset($p->id)) { break; }
			$partida[] = $p;
		}

		return $partida;
	}

	private static function diavase_arxio_theates($fp) {
		$theatis = array();
		while ($buf = self::get_line($fp)) { 
			$t = new Theatis($buf);
			if (!isset($t->pektis)) { break; }
			$theatis[] = $t;
		}

		return $theatis;
	}

	private static function diavase_arxio_sizitisi($fp) {
		$lid = -1;
		while ($buf = self::get_line($fp)) { 
			$lid = (int)($buf);
		}

		return $lid;
	}

	private static function get_line($fp) {
		$buf = Globals::get_line($fp);
		if (!$buf) { return FALSE; }
		if ($buf == DATA_END) { return FALSE; }
		return $buf;
	}

	private function diavase_db() {
		$this->partida = self::diavase_db_partides();
		$this->trepart = self::dikia_mou_partida($this->partida);	
		$this->thesi = self::dikia_mou_thesi($this->partida);	
		$this->theatis = self::diavase_db_theates();
		$this->sizitisi = self::diavase_db_sizitisi($this->trepart);
	}

	private static function diavase_db_partides() {
		global $globals;

		$partida = array();
		$query = "SELECT * FROM `partida` WHERE (`telos` IS NULL) AND " .
			"((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(`poll`)) < " .
			(POLLING_MAX_TIME + 10) . ") ORDER BY `id`";
		$result = $globals->query($query);
		while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
			$partida[] = new Partida($row);
		}

		return $partida;
	}

	private static function dikia_mou_partida(&$plist) {
		global $globals;

		for ($i = count($plist) - 1; $i >= 0; $i--) {
			if (($plist[$i]->pektis1 == $globals->pektis->login) ||
				($plist[$i]->pektis2 == $globals->pektis->login)) {
				return $plist[$i]->id;
			}
		}

		$query = "INSERT INTO `partida` (`pektis1`, `poll`) VALUES " .
			"('" . $globals->pektis->login . "', NOW())";
		$globals->query($query);
		$p = new Partida();
		$p->id = mysqli_insert_id($globals->db);
		$p->pektis1 = $globals->pektis->login;
		$plist[] = $p;
		return $p->id;
	}

	private static function dikia_mou_thesi($plist) {
		global $globals;

		for ($i = count($plist) - 1; $i >= 0; $i--) {
			if ($plist[$i]->pektis1 == $globals->pektis->login) { return 1; }
			if ($plist[$i]->pektis2 == $globals->pektis->login) { return 2; }
		}

		return 0;
	}

	private static function diavase_db_theates() {
		global $globals;

		$theatis = array();
		$query = "SELECT * FROM `theatis` ORDER BY `pektis`";
		$result = $globals->query($query);
		while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
			$theatis[] = new Theatis($row);
		}

		return $theatis;
	}

	private static function diavase_db_sizitisi($tp) {
		global $globals;

		$lid = -1;
		$query = "SELECT `id` FROM `sizitisi` WHERE `partida` = " .
			$tp . " ORDER BY `id` DESC LIMIT 1";
		$result = $globals->query($query);
		while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
			$lid = (int)($row[0]);
		}

		return $lid;
	}

	public function enimerosi_arxiou() {
		$fp = self::anixe_arxio("w");
		$this->enimerosi_arxiou_partida($fp);
		$this->enimerosi_arxiou_sizitisi($fp);
		fclose($fp);
	}

	private function enimerosi_arxiou_partida($fp) {
		Globals::put_line($fp, DATA_PARTIDA);
		$n = count($this->partida);
		for ($i = 0; $i < $n; $i++) {
			$this->partida[$i]->arxio($fp);
		}
		Globals::put_line($fp, DATA_END);
	}

	private function enimerosi_arxiou_sizitisi($fp) {
		if ($this->sizitisi < 0) { return; }
		Globals::put_line($fp, DATA_SIZITISI);
		Globals::put_line($fp, $this->sizitisi);
		Globals::put_line($fp, DATA_END);
	}
}
?>
